<?php

namespace App\Service\UserService;

use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Model\PssModel\PddToken;
use App\Service\VendorClient\ShopFenqileApi\ShopFenqileApiClient;
use App\Model\PssModel\FenQiLeGoods;
use Hyperf\Utils\WaitGroup;
use App\Amqp\Producer\FenQiLeMessageProducer;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Amqp\Producer;

/**
 * 分期乐服务中心
 * @author chenshubo
 */
class FQLService extends BaseService
{
    protected $FenQiLeClient;
    protected $config;
    
    /**
     * 接收消息数据
     * @param string $messageType
     * @param array $data
     */
    public function MessageRev(string $messageType,array $data)
    {
        return $this->{$messageType}($data);
    }
    
    /**
     * 商品消息变化
     * @param array $data
     */
    public function goodsChange(array $data)
    {
        $this->config = $config = $this->getConfig();
        $this->FenQiLeClient = new ShopFenqileApiClient($config);
        //开启协程
        $count = count($data);
        $wg = new WaitGroup();
        $wg->add($count);
        $result_update = [];
        foreach ($data as $goods)
        {
            co(function () use ($wg,$goods,& $result_update)
            {
                $response = $this->syncSingleFenQiLeGoods($goods);
                $result_update[] = $response;
                $wg->done();
            });
        }
        $wg->wait();
        return Normal::returnCode(Normal::SUC,"处理完成",$result_update);
    }
    
    /**
     * 商品批量下架
     * @param array $data
     */
    public function goodsSkuChange(array $data)
    {
        $config = $this->getConfig();
        $this->FenQiLeClient = new ShopFenqileApiClient($config);
        $produts = FenQiLeGoods::instance()
        ->select(['product_id'])
        ->whereIn('skucode',$data['skuList'])
        ->whereNotNull('product_id')
        ->get()
        ->toArray();
        if( empty($produts) ) {
            return Normal::returnCode(Normal::SUC,"没有满足的数据，无须处理");
        }
        
        //开启协程
        $count = count($produts);
        $wg = new WaitGroup();
        $wg->add($count);
        $result_update = [];
        foreach ($produts as $item)
        {
            co(function () use ($wg,$item,& $result_update)
            {
                $response = $this->FenQiLeClient->productDelistUpdate($item["product_id"]);
                $result_update[] = $response;
                $wg->done();
            });
        }
        $wg->wait();
        return Normal::returnCode(Normal::SUC,"处理完成",$result_update);
    }
    
    /**
     * 商品全量下架
     * @param array $data
     */
    public function goodsBatchDown(array $data)
    {
        $config = $this->getConfig();
        $this->FenQiLeClient = new ShopFenqileApiClient($config);

        //先查询出分期乐的所有商品
        $page = 1;
        while (true)
        {
            $query = [
                'page'      => $page,
                'pageSize'  => "10",
            ];
            $result_product = $this->FenQiLeClient->productGet($query);
            //如果没有商品就暂停查询
            if ($result_product['code'] != Normal::SUC  || empty($result_product["data"]["product_list_get_response"]["products"]))
            {
                break;
            }
            $result_product = $result_product["data"]["product_list_get_response"]["products"];
            //开始协助并发下架商品
            $product_count = count($result_product);
            $wg = new WaitGroup();
            $wg->add($product_count);
            foreach ($result_product as $product)
            {
                $product_id  =$product["product_id"];
                co(function () use ($product_id,$wg) {
                    $this->FenQiLeClient->productDelistUpdate($product_id);
                    $wg->done();
                });
            }
            $wg->wait();
            $page++;
        }
        return Normal::returnCode(Normal::SUC,"处理完成");
    }
    
    /**
     * 同步商品
     * @param array $goods
     */
    public function syncSingleFenQiLeGoods(array $goodsInfo)
    {
        $skuInfo        = current($goodsInfo['skuList']);
        $skucode        = $skuInfo['skucode'];
        //商品批次数据
        $storeList     = current($skuInfo['storeList']);
        $batchFirst    = current($storeList['goods_batch_list']);
        $firstSpec     = current($batchFirst['spec_list']);
        $goodsSpecAttr = $goodsInfo["goodsSpecAttr"];
        
        //判断是否向分期乐推送过商品，如果有，就执行更新操作，没有执行添加操作
        $FenqileGood  = FenQiLeGoods::instance()->info(['skucode' => $skucode]);
        if( !empty($FenqileGood['product_id']) && !empty($FenqileGood['sku_id']) )
        {
            return $this->goodsFenQiLeUpdate($goodsInfo,$FenqileGood);
        }
        else
        {
            $return = $this->goodsFenQiLeAdd($goodsInfo,$FenqileGood);
            if( $return['code'] != Normal::SUC ) {
                return Normal::returnCode(Normal::FAIL,"goodsFenQiLeAdd接口查询失败【{$return['msg']}】",$return);
            }
            return $this->goodsFenQiLeUpdate($goodsInfo,$return['data']['FenQiLeGoods']);
        }
    }
    
    /**
     * 分期乐更新
     * @param array $goods
     * @param array $FenqileGood
     */
    public function goodsFenQiLeUpdate(array $goodsInfo,array $FenqileGood)
    {
        $skuInfo        = current($goodsInfo['skuList']);
        $skucode        = $skuInfo['skucode'];
        //商品批次数据
        $storeList     = current($skuInfo['storeList']);
        $batchFirst    = current($storeList['goods_batch_list']);
        $firstSpec     = current($batchFirst['spec_list']);
        $goodsSpecAttr = $goodsInfo["goodsSpecAttr"];
        $sku_id         = $FenqileGood["sku_id"];
        $product_id     = $FenqileGood["product_id"];
        
        //进行批量调用接口
        $goodsUpdateAllItemList = [];
        
        //产品新增
        $goodsUpdateAllItemList[] = [
            'method'    => 'productUpdate',
            'data'      => [
                "product_id"       => $product_id,
                "product_name"     => $goodsInfo["goodsName"],
                "product_desc"     => $goodsInfo["goodsName"],
                "third_product_id" => $skucode,
            ]
        ];
        
        //产品更新上架
        $goodsUpdateAllItemList[] = [
            'method'    => 'productlistUpdate',
            'data'      => [
                "product_id" => $product_id,
            ]
        ];
        
        //产品详情更新
        $goodsUpdateAllItemList[] = [
            'method'    => 'productDetailUpdate',
            'data'      => [
                "product_id"    => $product_id,
                "detail[text]"  => $goodsInfo["description"],
            ]
        ];
        
        //sku价格更新
        $goodsUpdateAllItemList[] = [
            'method'    => 'skuUpdate',
            'data'      => [
                "sku_id"        => $sku_id,
                "third_sku_id"  => $skucode,
                "amount"        => $firstSpec['priceSettlement'], //sku 结算价
                "mart_amount"   => $firstSpec['priceMarket'], //sku 原价，单位元，小数点最多保留 2 位
            ]
        ];
        
        //sku库存更新
        $goodsUpdateAllItemList[] = [
            'method'    => 'skuQuantityUpdate',
            'data'      => [
                "sku_id"        => $sku_id,
                "num"           => $batchFirst["num"],
            ]
        ];
        
        //sku详情更新
        $goodsUpdateAllItemList[] = [
            'method'    => 'skuDetailUpdate',
            'data'      => [
                "sku_id"        => $sku_id,
                "description"   => $goodsInfo["description"],
            ]
        ];
        
        //开启协程
        $count = count($goodsUpdateAllItemList);
        $wg = new WaitGroup();
        $wg->add($count);
        $result_update = [];
        foreach ($goodsUpdateAllItemList as $item)
        {
            co(function () use ($wg,$item,& $result_update)
            {
                $response = $this->FenQiLeClient->{$item['method']}($item['data']);
                $result_update[] = [
                    'method'    => $item['method'],
                    'response'  => $response
                ];
                $wg->done();
            });
        }
        $wg->wait();
        $contents = [
            'product_id' => $product_id,
            'sku_id'     => $sku_id,
            'images'     => $goodsInfo['images']
        ];
        $message = new FenQiLeMessageProducer($contents);
        $producer = ApplicationContext::getContainer()->get(Producer::class);
        $producer->produce($message);
        return Normal::returnCode(Normal::SUC,"处理完成",$result_update);
    }
    
    /**
     * 处理单个商品同步
     * @param string $product_id
     * @param array $product_id
     */
    public function uploadSingleProductImageByProductID(string $product_id,string $sku_id,array $images)
    {
        $this->config = $config = $this->getConfig();
        $this->FenQiLeClient = new ShopFenqileApiClient($config);
        //查询商品详情
        $result_product = $this->FenQiLeClient->productQuery([
            'product_id'    => $product_id
        ]);
        if( $result_product['code'] != Normal::SUC ) {
            return Normal::returnCode(Normal::FAIL,"productQuery接口查询失败【{$result_product['msg']}】",$result_product);
        }
        
        //获取图片，删除数据
        $pic_ids = [];
        if( !empty($result_product['data']['product_detail_get_response']['product']['pic_list']) ) {
            $pic_list = $result_product['data']['product_detail_get_response']['product']['pic_list'];
            $pic_ids  = array_column($pic_list,'pic_id');
        }
        
        if( !empty($pic_ids) ) {
            $result_product_image_delete = $this->FenQiLeClient->productImageDelete([
                'product_id'    => $product_id,
                'pic_ids'       => \implode(",", $pic_ids)
            ]);
            if( $result_product_image_delete['code'] != Normal::SUC ) {
                return Normal::returnCode(Normal::FAIL,"productQuery接口查询失败【{$result_product_image_delete['msg']}】",$result_product_image_delete);
            }
        }
        
        //循环一个个得上传更新图片
        $result_all = [];
        foreach ($images as $imageUrl)
        {
            $result_all[] = $this->FenQiLeClient->productImageUpload([
                "product_id"    => $product_id,
                "image"         => $imageUrl,
            ]);
        }
        //更新列表页图片
        $sku_image    = $images[0];
        if($sku_image){
            $result_all[] = $this->FenQiLeClient->skuImageUpload([
                "sku_id"    => $sku_id,
                "image"     => $sku_image,
            ]);
        }
        return Normal::returnCode(Normal::SUC,"处理完成",$result_all);
    }
    
    
    /**
     * 分期乐商品新增
     * @param array $goods
     * @param array $FenqileGood
     */
    public function goodsFenQiLeAdd(array $goodsInfo,array $FenqileGood)
    {
        $skuInfo        = current($goodsInfo['skuList']);
        $skucode        = $skuInfo['skucode'];
        //商品批次数据
        $storeList      = current($skuInfo['storeList']);
        $batchFirst     = current($storeList['goods_batch_list']);
        $firstSpec      = current($batchFirst['spec_list']);
        $goodsSpecAttr  = $goodsInfo["goodsSpecAttr"];
        
        //查询product是否添加过
        if( empty($FenqileGood) || empty($FenqileGood['product_id']) )
        {
            $pushData = [
                "product_name"     => $goodsInfo["goodsName"],
                "product_desc"     => $goodsInfo["goodsName"],
                "start_time"       => date("Y-m-d H:i:s", time()),
                "delivery_type"    => "1",
                "third_product_id" => $skucode
            ];
            $result_productAdd = $this->FenQiLeClient->productAdd($pushData);
            if( $result_productAdd['code'] != Normal::SUC ) {
                return Normal::returnCode(Normal::FAIL,"productAdd fail【{$result_productAdd['msg']}】",$result_productAdd);
            }
            
            $product_id = $result_productAdd['data']['product_add_response']['product']['product_id'];
            if( empty($FenqileGood) ) {
                FenqileGoods::instance()->add([
                    'skucode'    => $skucode,
                    'product_id' => $product_id,
                    'cd'         => time(),
                ]);
            } else {
                FenqileGoods::instance()->where('skucode',$skucode)->update([
                    'product_id'    =>  $product_id,
                    'md'            => time(),
                ]);                
            }
        } else {
            $product_id = $FenqileGood['product_id'];
        }
        
        //添加sku数据        
        if( empty($FenqileGood['sku_id']) ) 
        {
            $skuData = [
                "product_id"    => $product_id,
                "third_sku_id"  => $skucode,
                "sku_num"       => $batchFirst['num'], //sku 库存
                "amount"        => $firstSpec['priceSettlement'], //sku 结算价
                "mart_amount"   => $firstSpec['priceMarket'], //sku 原价，单位元，小数点最多保留 2 位
            ];
            $result_sku_add = $this->FenQiLeClient->skuAdd($skuData);
            if( $result_sku_add['code'] != Normal::SUC ) {
                return Normal::returnCode(Normal::FAIL,"skuAdd fail【{$result_sku_add['msg']}】",$result_sku_add);
            }
            
            $sku_id = $result_sku_add['data']['sku_add_response']['item']['sku_id'];
            FenqileGoods::instance()->where('skucode',$skucode)->update([
                'sku_id'    => $sku_id,
                'md'        => time()
            ]);
        } else {
            $sku_id = $FenqileGood['sku_id'];
        }
        return Normal::returnCode(Normal::SUC,"处理完成",[
            'FenQiLeGoods'  => [
                'skucode'       => $skucode,
                'product_id'    => $product_id,
                'sku_id'        => $sku_id,
            ]
        ]);
    }
    
    private function getConfig()
    {
        $config = PddToken::instance()->info(['auth_type'=>PddToken::AUTH_TYPE_FENQILE]);
        return $config;
    }
}